import {securityStore} from "./observable";
import _router from '@/router'
import {cloneDeep} from 'lodash'

/**
 * 检查是否拥有权限
 * @param code
 * @returns {boolean}
 */
export function hasPermission(code) {
  const auth_code = securityStore.observe.authCode || []
  //return true
  return code === "*" || auth_code.includes(code)
}

/**
 * 基于权限过滤路由的迭代函数
 * @param route
 * @returns {object|undefined|[]}
 */
function routeAuthAssertIterate(route) {
  if (route instanceof Array) {
    return route.map(entry => routeAuthAssertIterate(entry)).filter(entry => !_.isEmpty(entry))
  } else {
    if (!_.isEmpty(route.meta.auth)) {
      if (hasPermission(route.meta.auth.code)) {
        //没有配置权限或者配置的权限已授权
        if (route.children) {
          route.children = routeAuthAssertIterate(route.children)
        }
        return route
      }
    } else {
      return route
    }
  }
}

/**
 * 将路由配置转换为资源信息的迭代函数
 * @param route
 * @param parent
 * @returns {object|undefined|[]}
 */
function routeConvertResourceIterate(route, parent) {
  if (route instanceof Array) {
    return route.map(entry => routeConvertResourceIterate(entry, parent)).filter(entry => !_.isEmpty(entry))
  } else {
    //配置了权限、菜单
    if (route.meta.auth && route.meta.menu) {
      let menuTreeData = {name: route.meta.menu.title, ...route.meta.auth}
      //非跳转容器
      if (!(route.redirect && route.meta.container)) {
        if (route.children) {
          menuTreeData.children = routeConvertResourceIterate(route.children, route)
        }
      }
      return menuTreeData
    }
  }
}

/**
 * 将路由数据转换资源注册数据
 */
export function routerToResourceHandler() {
  return routeConvertResourceIterate(cloneDeep(_router.options.routes))
}

/**
 * 路由权限处理器
 */
export function routeAuthHandler() {
  let authMenuRouter = routeAuthAssertIterate(cloneDeep(_router.options.routes))
  return authMenuRouter
}
